﻿using Android.App;
using Android.Widget;
using Android.OS;
using Android.Support.V7.App;
using Android.Views;
using System.Collections.Generic;
using Android.Net.Wifi;
using Android.Content;
using Java.Net;
using Android.Text.Format;
using Java.Lang;
using System.Text;
using System;

namespace PCControl
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTask)]
    public class MainActivity : AppCompatActivity, Android.Views.View.IOnClickListener, AdapterView.IOnItemSelectedListener, MyService.IOnMyServiceListener
    {
        Button btn_Connect;
        Button btn_Disconnect;
        Button btn_Close;
        Button btn_Send;
        Button btn_Clear;
        Button btn_PlayPause;
        Button btn_MediaPrev;
        Button btn_MediaNext;
        Spinner spinner;
        EditText editText;


        private class Connection : Java.Lang.Object, IServiceConnection
        {
            MainActivity mMainActivity;
            public Connection(MainActivity mainActivity)
            {
                mMainActivity = mainActivity;
            }

            public void OnServiceConnected(ComponentName name, IBinder service)
            {
                if (mMainActivity.myBinder == null)
                {
                    mMainActivity.myBinder = service as MyService.MyBinder;
                    mMainActivity.myBinder.SetOnMyServiceListener(mMainActivity);
                    mMainActivity.UpdateNotification("控制器正在运行", "PCControl");
                }
                switch (mMainActivity.myBinder.GetState())
                {
                    case MyService.MYSERVICE_STATE_CONNECTED:
                    case MyService.MYSERVICE_STATE_CONNECTING:
                        mMainActivity.btn_Connect.Enabled = false;
                        break;
                }
            }

            public void OnServiceDisconnected(ComponentName name)
            {
            }
        }
        MyService.MyBinder myBinder;
        private Connection connection;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            btn_Connect = (Button)FindViewById(Resource.Id.btn_connect);
            btn_Connect.SetOnClickListener(this);
            btn_Disconnect = (Button)FindViewById(Resource.Id.btn_disconnect);
            btn_Disconnect.SetOnClickListener(this);
            btn_Disconnect.Enabled = false;
            btn_Close = (Button)FindViewById(Resource.Id.btn_close);
            btn_Close.SetOnClickListener(this);

            btn_Send = FindViewById<Button>(Resource.Id.btn_sendCMD);
            btn_Send.SetOnClickListener(this);
            btn_Send.Enabled = false;

            btn_Clear = FindViewById<Button>(Resource.Id.btn_Clear);
            btn_Clear.SetOnClickListener(this);
            btn_PlayPause = FindViewById<Button>(Resource.Id.btn_PlayPause);
            btn_PlayPause.SetOnClickListener(this);
            btn_MediaPrev = FindViewById<Button>(Resource.Id.btn_MediaPrev);
            btn_MediaPrev.SetOnClickListener(this);
            btn_MediaNext = FindViewById<Button>(Resource.Id.btn_MediaNext);
            btn_MediaNext.SetOnClickListener(this);

            FindViewById<Button>(Resource.Id.btn_poweron).SetOnClickListener(this);

            spinner = (Spinner)FindViewById(Resource.Id.spinner_cmdList);
            spinner.Enabled = false;
            var aTmp = @"播放/暂停
停止
上一曲
下一曲
音量+
音量-
静音
关机";
            var list = new List<string>(aTmp.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
            var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, list);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;
            spinner.OnItemSelectedListener = this;

            editText = FindViewById<EditText>(Resource.Id.editText1);
            editText.SetOnKeyListener(null);
            myHandler = new MyHandler(this);
            connection = new Connection(this);
            Intent intent = new Intent(this, typeof(MyService));
            StartService(intent);
            BindService(intent, connection, Bind.AutoCreate);

        }

        public void UpdateNotification(string contentTitle, string contentText)
        {
            NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            Notification notification = new Notification(Resource.Mipmap.ic_launcher, "控制器正在运行");
            Intent intent = new Intent(this, typeof(MainActivity));
            PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);
            notification.SetLatestEventInfo(this, contentTitle, contentText, pendingIntent);
            myBinder.mService.StartForeground(1, notification);
        }
        public void OnClick(View v)
        {
            switch (v.Id)
            {
                // 连接
                case Resource.Id.btn_connect:
                    myBinder.Search();
                    break;
                case Resource.Id.btn_disconnect:
                    myBinder.DisConnect();
                    break;
                case Resource.Id.btn_close:
                    Intent intent = new Intent(this, typeof(MyService));
                    StopService(intent);
                    UnbindService(connection);
                    Java.Lang.JavaSystem.Exit(0);
                    break;
                case Resource.Id.btn_sendCMD:
                    SendCommand(spinner.SelectedItem.ToString());
                    break;
                case Resource.Id.btn_poweron:
                    AquilaWolLibrary.WakeUp("1C-1B-0D-0A-46-DD");
                    AquilaWolLibrary.WakeUp("00-E0-4C-20-19-88");
                    AquilaWolLibrary.WakeUp("7D-4D-7B-B2-FE-4B");
                    break;
                case Resource.Id.btn_Clear:
                    editText.Text = "";
                    break;
                case Resource.Id.btn_PlayPause:
                case Resource.Id.btn_MediaPrev:
                case Resource.Id.btn_MediaNext:
                    SendCommand(((Button)v).Text);
                    break;
            }
        }

        public void OnItemSelected(AdapterView parent, View view, int position, long id)
        {
        }

        public void OnNothingSelected(AdapterView parent)
        {
        }
        class MyThread : Thread
        {
            MainActivity mMainActivity;
            string CMD;
            public MyThread(string cmd, MainActivity mainActivity)
            {
                CMD = cmd;
                mMainActivity = mainActivity;
            }
            public override void Run()
            {
                mMainActivity.myBinder.SendCommand(CMD);
            }
        }
        public void SendCommand(string cmd)
        {
            new MyThread(cmd, this).Start();
        }
        void SendBroadCastToCenter()
        {

            DatagramSocket theSocket = null;
            try
            {
                InetAddress server = InetAddress.GetByName("255.255.255.255");
                theSocket = new DatagramSocket();
                var data = Encoding.UTF8.GetBytes("01握手");
                DatagramPacket theOutput = new DatagramPacket(data, data.Length, server, 6789);
                /*这一句就是发送广播了，其实255就代表所有的该网段的IP地址，是由路由器完成的工作*/
                theSocket.Send(theOutput);
            }
            catch (Java.Lang.Exception e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                if (theSocket != null)
                    theSocket.Close();
            }
        }
        public override bool DispatchKeyEvent(KeyEvent e)
        {
            if (e.Action == KeyEventActions.Down)
            {
                Keycode code = e.KeyCode;
                switch (code)
                {
                    case Keycode.VolumeUp:
                        SendCommand("音量+");
                        return true;
                    case Keycode.VolumeDown:
                        SendCommand("音量-");
                        return true;
                }
            }
            return base.DispatchKeyEvent(e);
        }
        class MyHandler : Handler
        {
            MainActivity mMainActivity;
            public MyHandler(MainActivity mainActivity)
            {
                mMainActivity = mainActivity;
            }
            public override void HandleMessage(Message msg)
            {
                base.HandleMessage(msg);
                string m = (string)msg.Obj;
                mMainActivity.editText.Append(m + "\r\n");
                mMainActivity.UpdateNotification("电脑控制器", m);
                switch (msg.What)
                {
                    case 10:
                        mMainActivity.btn_Connect.Enabled = false;
                        mMainActivity.btn_Disconnect.Enabled = true;
                        mMainActivity.btn_Send.Enabled = true;
                        mMainActivity.spinner.Enabled = true;
                        break;
                    case 6:
                    case 99:
                        mMainActivity.btn_Connect.Enabled = true;
                        mMainActivity.btn_Disconnect.Enabled = false;
                        mMainActivity.btn_Send.Enabled = false;
                        mMainActivity.spinner.Enabled = false;
                        break;
                    case 5:
                        break;
                }
            }
        }
        MyHandler myHandler;
        public void OnConnectSuccess()
        {
            Message m = new Message
            {
                What = 10,
                Obj = "连接成功"
            };
            myHandler.SendMessage(m);
        }

        public void OnConnectError(string errMsg)
        {
            Message m = new Message
            {
                What = 99,
                Obj = "连接错误：" + errMsg
            };
            myHandler.SendMessage(m);
        }

        public void OnConnecting(string msg)
        {
            Message m = new Message
            {
                What = 5,
                Obj = "连接中：" + msg
            };
            myHandler.SendMessage(m);
        }

        public void OnDisConnect()
        {
            Message m = new Message
            {
                What = 6,
                Obj = "断开连接"
            };
            myHandler.SendMessage(m);
        }

        public void OnCommandSendSuccess(string cmd)
        {
            Message m = new Message
            {
                What = 8,
                Obj = "命令：" + cmd + " 发送成功"
            };
            myHandler.SendMessage(m);
        }
    }
}

